package lm.concurrency.pattern.arrunning;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;

/**
 * 交替运行模式
 */
@Slf4j
public class AlterateRunningDemo {
    public static void main(String[] args) throws Exception {
        waitNotifyTest();
//        awaitSignalTest();
//        parkUnparkTest();
    }

    private static void parkUnparkTest() {
        ParkUnpark pu = new ParkUnpark(5);
        Thread t1,t2 = null,t3 = null;
        Thread finalT = t2;
        t1 = new Thread(() -> {
            pu.print("a", finalT);
        });
        Thread finalT1 = t3;
        t2 = new Thread(() -> {
            pu.print("b", finalT1);
        });
         t3 = new Thread(() -> {
            pu.print("c", t1);
        });
        t1.start();
        t2.start();
        t3.start();
        LockSupport.unpark(t1);
    }

    private static void awaitSignalTest() throws InterruptedException {
        AwaitSignal awaitSignal = new AwaitSignal(5);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();
        new Thread(() -> {
            awaitSignal.print("a", a, b);
        }).start();
        new Thread(() -> {
            awaitSignal.print("b", b, c);
        }).start();
        new Thread(() -> {
            awaitSignal.print("c", c, a);
        }).start();

        Thread.sleep(1000);
        awaitSignal.lock();
        try {
            System.out.println("开始...");
            a.signal();
        } finally {
            awaitSignal.unlock();
        }
    }

    private static void waitNotifyTest() {
        WaitNotify wn = new WaitNotify(1, 5);
        new Thread(() -> {
            wn.print("a", 1, 2);
        }).start();
        new Thread(() -> {
            wn.print("b", 2, 3);
        }).start();
        new Thread(() -> {
            wn.print("c", 3, 1);
        }).start();
    }
}

